import { storage } from '@/store/sessionStorage'
import { KeepLoginCountDown, regMobile } from '@/utils'
import { ref, reactive } from 'vue'
import { CxlMessage } from '@/components/message'
import { login } from '@/apis/login'
import { getUserInfo } from '@/apis/home'

import { DisableShare } from '@/utils/disableShare'

export class LoginData extends DisableShare {
    //数据
    data = reactive({
        phone: '',
        password: '',
        checked: false
    })

    //弹窗数据
    dialog = reactive({
        visible: false
    })
    //审核中弹窗
    auditVisible = ref(false)
    //审核失败弹窗
    failVisible = ref(false)

    isClickLogin = false
    //是否勾选了协议
    isSelectCheck = ref(true)
    constructor() {
        super()
    }

    /**
     * 账号是否验证通过，验证输入的账号是否是正确的手机号
     * @param rule
     * @param value
     * @param callback
     */
    userNameValidatePass(rule: any, value: any, callback: any) {
        if (value === '') {
            callback(new Error('请输入手机号码'))
        } else {
            regMobile(value) ? callback() : callback(new Error('手机号有误，请重新输入'))
        }
    }
    //监听勾选协议
    onCheckChange = () => {
        this.isSelectCheck.value = true
    }
    /**
     * 提交验证（手机号验证+密码是否为空）
     * 验证通过调用登录接口进行登录
     */
    onSubmitLogin = (phoneRef: any, passwordRef: any) => {
        // console.log(phoneRef?.validateInput())
        //判断协议是否勾选
        if (!this.data.checked) {
            this.isSelectCheck.value = false
        }
        const a = phoneRef?.validateInput()
        const b = passwordRef?.validateInput()
        if (a && b && this.isSelectCheck.value) {
            console.log('phone', this.data.phone, 'password', this.data.password)
            const formadate = new FormData()
            formadate.append('phone', this.data.phone)
            formadate.append('password', this.data.password)
            if (!this.isClickLogin) {
                this.isClickLogin = true
                login(formadate).then((res: any) => {
                    const code = res.data.value
                    this.isClickLogin = false
                    console.log('code', res)
                    /**
                     * 10004 审核中
                     * 10005 审核不通过
                     * 10006 账号未注册
                     * 10007 账号|密码错误
                     */
                    if (code === 10006) {
                        //账号未注册
                        CxlMessage.error({ content: '您输入的账号不存在！' })
                        // this.dialog.visible = true
                    } else if (code === 10004) {
                        //审核中
                        // CxlMessage.warning('信息正在审核中！')
                        this.auditVisible.value = true
                    } else if (code === 2) {
                        //审核通过
                        // CxlMessage.success('恭喜您，审核通过啦！')
                    } else if (code === 10005) {
                        //审核不通过
                        console.log('account verification failed')
                        // CxlMessage.error('很抱歉，您的审核没有通过！')
                        this.failVisible.value = true
                    } else if (code === 200) {
                        CxlMessage.success('登录成功！')
                        //登录成功
                        const expireTime: number = Number(res.data.data.expire) - 5
                        console.log('login succeed')
                        storage.set('token', res.data.data.accessToken)
                        storage.set('refreshToken', res.data.data.refreshToken)
                        //保留首次登录的时间
                        storage.set('loginTime', new Date().getTime().toString())
                        //保持登录过期时间expire 秒
                        storage.set('expire', '' + expireTime)
                        //设置保持登录状态
                        storage.set('keepLoginStatus', 'true')
                        storage.set('loginStatus', 'true')

                        this.uStore.token = res.data.data.accessToken
                        this.uStore.loginStatus = true

                        new KeepLoginCountDown(Number(expireTime) / 1).start()

                        //获取用户信息
                        getUserInfo().then((res: any) => {
                            if (res.data.value === 200) {
                                storage.set('userInfo', JSON.stringify(res.data.data))
                                storage.set('isAdmin', !res.data.data.isChild + '')

                                this.uStore.isAdmin = !res.data.data.isChild

                                console.log('管理员', this.uStore.isAdmin)

                                this.router.replace({
                                    path: '/index'
                                })
                            }
                        })
                    } else if (code === 10007) {
                        //登录失败 账号|密码错误
                        CxlMessage.error({ content: res.data.desc })
                    } else {
                        //登录失败
                        CxlMessage.error({ content: res.data.desc })
                    }
                })
            }
        }
    }
    /**
     * 跳转到指定路由
     * @param url
     */
    onSkip = (el: any) => {
        console.log(el.target.dataset.url)
        this.router.push({ path: el.target.dataset.url })
    }

    /**
     * 打开协议
     */
    onOpenProtocol = (el: any) => {
        console.log(el.target.dataset.type)
        this.router.push({ name: 'protocol', params: { type: el.target.dataset.type } })
    }
}
